package com.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.Chapter;
import com.edu.entity.Video;
import com.edu.entity.chapter.ChapterVo;
import com.edu.entity.chapter.VideoVo;
import com.edu.entity.vo.CourseQuery;
import com.edu.mapper.ChapterMapper;
import com.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author mxs
 * @since 2021-10-21
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    VideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoVoByCourseId(String  courseId) {
        //根据id获取chapter列表
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        //获取当前课程的chapter类列表
        List<Chapter> chapterList = baseMapper.selectList(queryWrapper);

        //获得当前课程的video类列表
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        List<Video> videoList = videoService.list(videoQueryWrapper);

        //创建最终展示的列表
        List<ChapterVo> finalList = new ArrayList<>();

        for (Chapter chapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            //将chapter的值赋给chapter类
            BeanUtils.copyProperties(chapter, chapterVo);
            for (Video video : videoList) {
                if (video.getChapterId().equals(chapterVo.getId())) {
                    //将二级分类添加到一级分类中
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    chapterVo.getChildren().add(videoVo);
                }
            }
            //将一级分类添加到最终列表中
            finalList.add(chapterVo);
        }
        //返回最终列表
        return finalList;
    }

    @Override
    public CourseQuery getCourseInfoById(Long courseId) {
        Chapter chapter = baseMapper.selectById(courseId);
        return null;
    }

    @Override
    public Boolean deleteChapter(String chapterId) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        //查询是否有小节
        queryWrapper.eq("chapter_id", chapterId);
        //
        int count = videoService.count(queryWrapper);
        if (count > 0) {
            //说明有小节不删除，返回false
            return false;
        } else {
            int delete = baseMapper.deleteById(chapterId);
            //返回删除结果
            return delete > 0;
        }

    }
}
